package com.edu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.client.VodClient;
import com.edu.config.exceptionHandler.exception.GuliException;
import com.edu.entity.Chapter;
import com.edu.entity.Course;
import com.edu.entity.Video;
import com.edu.entity.vo.CoursePublishVo;
import com.edu.entity.vo.CourseQuery;
import com.edu.mapper.CourseMapper;
import com.edu.service.ChapterService;
import com.edu.service.CourseDescriptionService;
import com.edu.service.CourseService;
import com.edu.service.VideoService;
import com.edu.utils.R;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author mxs
 * @since 2021-10-21
 */
@RestController
@RequestMapping("/edu/course")
@CrossOrigin
@Api("课程管理")
public class CourseController {
    @Autowired
    private CourseService courseService;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseDescriptionService descriptionService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private VideoService videoService;
    @Autowired
    private VodClient vodClient;

    /**
     * 添加课程信息和课程描述
     *
     * @param courseQuery
     * @return
     */
    @PostMapping("/addCourseInfo")
    public R saveCourseInfo(@RequestBody(required = true) CourseQuery courseQuery) {
        String id = courseService.saveCourseInfo(courseQuery);
        return R.success().data("courseId", id);
    }

    /**
     * 根据课程id获取课程信息
     *
     * @param courseId
     * @return
     */
    @GetMapping("/getCourseInfoByCourseId/{courseId}")
    public R getCourseInfoByCourseId(@PathVariable Long courseId) {
        CourseQuery courseInfo = courseService.getCourseInfoByCourseId(courseId);
        return R.success().data("courseInfo", courseInfo);
    }

    /**
     * 更新课程信息
     *
     * @param courseInfo 课程信息 + 课程描述
     * @return
     */
    @PostMapping("/updateCourseInfo")
    public R updateCourseInfo(@RequestBody(required = true) CourseQuery courseInfo) {
        courseService.updateCourseInfo(courseInfo);
        return R.success();
    }

    /**
     * 更新课程
     *
     * @param course
     * @return
     */
    @PostMapping("/update")
    public R updateCourse(@RequestBody Course course) {
        boolean update = courseService.updateById(course);
        return R.success();
    }

    @GetMapping("/getPublish/{courseId}")
    public R getCoursePublish(@PathVariable String courseId) {
        CoursePublishVo coursePublish = courseService.getCoursePublish(courseId);
        return R.success().data("publish", coursePublish);
    }

    /**
     * 最终发布课程，并且将课程状态改成normal
     *
     * @param courseId
     * @return
     */
    @PostMapping("/publishCourse/{courseId}")
    public R publishCourse(@PathVariable String courseId) {

        boolean update = courseMapper.updateCourseId(courseId);
        System.out.println(update);
        return R.success();
    }

    /**
     * 带条件分页查询课程信息
     *
     * @param pageNo
     * @param limit
     * @param courseQuery
     * @return
     */
    @PostMapping("/getCourseInfo/{pageNo}/{limit}")
    public R getCourseInfo(@PathVariable long pageNo,
                           @PathVariable long limit,
                           @RequestBody(required = false) Course courseQuery) {
        QueryWrapper<Course> queryWrapper = courseService.getCourseQueryWrapper(courseQuery);
        Page<Course> page = new Page<>(pageNo, limit);
        IPage<Course> coursePage = courseService.page(page, queryWrapper);
        List<Course> records = coursePage.getRecords();
        long total = coursePage.getTotal();
        return R.success().data("list", records).data("total", total);
    }

    /**
     * 根据id删除课程
     *
     * @param courseId
     * @return
     */
    @DeleteMapping("/deleteCourse/{courseId}")
    public R reomoveCourseBy(@PathVariable String courseId) {
        //删除课程小节
        QueryWrapper<Video> videoWrapper = new QueryWrapper<>();
        videoWrapper.eq("course_id", courseId);
        //只查询video_source_id
        videoWrapper.select("video_source_id");
        //查询该课程的所有视频
        List<Video> videoList = videoService.list(videoWrapper);
        //获取视频的id集合
        List<String> videoIds = new ArrayList<>();
        for (Video video : videoList) {
            if (!StringUtils.isEmpty(video.getVideoSourceId())) {
                //先判空
                videoIds.add(video.getVideoSourceId());
            }
        }
        //删除所有视频
        if (videoIds.size() > 0) {
            //有视频才执行删除
            R r = vodClient.removeVideos(videoIds);
            if (r.getCode() == 20001){
                throw new GuliException(20001,"删除视频失败，熔断器...");
            }
        }

        videoService.remove(videoWrapper);
        //删除课程章节
        QueryWrapper<Chapter> courseWrapper = new QueryWrapper<>();
        courseWrapper.eq("course_id", courseId);
        chapterService.remove(courseWrapper);
        //删除课程描述
        descriptionService.removeById(courseId);
        //删除课程本身
        courseService.removeById(courseId);
        return R.success();
    }
}

